package net.jjjshop.front.controller.lbt;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.jjjshop.common.constants.ConfConstants;
import net.jjjshop.common.entity.lbt.JybBusinessOrderEntity;
import net.jjjshop.common.entity.lbt.JybBusinessOrderRequest;
import net.jjjshop.common.entity.lbt.LbSysConfigEntity;
import net.jjjshop.common.entity.lbt.LbUserWalletEntity;
import net.jjjshop.common.entity.user.User;
import net.jjjshop.common.service.lbt.JybBusinessOrderService;
import net.jjjshop.common.service.lbt.LbSysConfigService;
import net.jjjshop.common.service.lbt.LbUserWalletService;
import net.jjjshop.common.service.lbt.UserBillService;
import net.jjjshop.common.service.user.UserService;
import net.jjjshop.common.util.BigDecimalUtil;
import net.jjjshop.framework.common.api.ApiResult;
import net.jjjshop.framework.util.LoginUtil;
import net.jjjshop.front.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;


/**
 * 挂卖回收金币订单表 控制器
 */
@RestController
@RequestMapping("/front/jybbusinessorder")
@Api(tags = "挂卖回收金币订单表")
public class JybBusinessOrderController extends BaseController {
    @Autowired
    private JybBusinessOrderService jybBusinessOrderService;
    @Autowired
    private LbUserWalletService walletService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserBillService userBillService;

    @Autowired
    private LbSysConfigService configService;
    /**
     * 列表信息
     */
    @ApiOperation(value = "列表信息")
    @GetMapping("/list")
    public ApiResult<IPage<JybBusinessOrderEntity>> list(JybBusinessOrderRequest bean, Integer page, Integer limit){

        return ApiResult.ok(jybBusinessOrderService.getList(bean,page,limit));
    }



    /**
     * 详情数据
     */
    @ApiOperation(value = "详情数据")
    @GetMapping("/info/{id}")
    public ApiResult<JybBusinessOrderEntity> info(@PathVariable("id") Integer id){
		JybBusinessOrderEntity jybBusinessOrder = jybBusinessOrderService.getById(id);

        return ApiResult.ok(jybBusinessOrder);
    }

    /**
     * 新增数据
     */
    @ApiOperation(value = "新增数据")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/save")
    public ApiResult<String> save(@RequestBody @Validated JybBusinessOrderEntity jybBusinessOrder){
        User user = userService.getById(LoginUtil.getUserId());
//        if (user.getOrderNum() <= 0){
//            return ApiResult.fail("您还未激活账户");
//        }
        jybBusinessOrder.setCreateTime(new Date());
        jybBusinessOrder.setUid(LoginUtil.getUserId());
        jybBusinessOrder.setAppId(10001);
        LbSysConfigEntity configEntity = configService.selectSysConfig();
        BigDecimal ps = configEntity.getTzMin();
        if (null != configEntity){
            if (null !=configEntity.getTzMin()){
                if (configEntity.getTzMin().doubleValue() < 1){
                    ps = new BigDecimal(1);
                }
            }else{
                ps = new BigDecimal(1);
            }
        }else{
            ps = new BigDecimal(1);
        }
        jybBusinessOrder.setPrice(ps);
        if (jybBusinessOrder.getType() == 1) {
            //挂卖处理
            LbUserWalletEntity walletInfo = walletService.getUserWalletInfo(jybBusinessOrder.getUid());
            if (null == walletInfo || null == walletInfo.getId()) {
                return ApiResult.fail("没有找到钱包");
            }
            if (jybBusinessOrder.getClassType() == 0){
                //处理挂卖权益卡
                if (null == walletInfo.getScore() || walletInfo.getScore().doubleValue() <= 0) {
                    return ApiResult.fail("没有可交易权益卡");
                }
                BigDecimal total = BigDecimalUtil.mul(jybBusinessOrder.getNum(), new BigDecimal(ConfConstants.HANG_SALE_FEES));
                //扣除手续费百分之比
                BigDecimal allPrice = BigDecimalUtil.addDouble(jybBusinessOrder.getNum(),total );
                //
                if (walletInfo.getScore().doubleValue() < allPrice.doubleValue()) {
                    return ApiResult.fail("出售数量不够");
                }
                walletInfo.setScore(BigDecimalUtil.subDouble(walletInfo.getScore(), allPrice));
                if(! userBillService.addBillRecord("委托出售权益卡",ConfConstants.INTEGRAL_TYPE,0,allPrice,userService.getUserId(),null)){
                    throw new RuntimeException("卖出异常");
                }
                if (jybBusinessOrderService.save(jybBusinessOrder)) {
                    if (walletService.updateById(walletInfo)) {
                        return ApiResult.ok("发布成功");
                    } else {
                        throw new RuntimeException("挂卖异常");
                    }

                }
            }else if (jybBusinessOrder.getClassType() == 1){
                jybBusinessOrder.setPrice(new BigDecimal(1));
                //处理佣金挂卖
                if (null == walletInfo.getMoney() || walletInfo.getMoney().doubleValue() <= 0) {
                    return ApiResult.fail("没有可交易贡献值");
                }
                if (walletInfo.getMoney().doubleValue() < jybBusinessOrder.getNum().doubleValue()) {
                    return ApiResult.fail("出售数量不够");
                }
                BigDecimal total = BigDecimalUtil.mul(jybBusinessOrder.getNum(), new BigDecimal(ConfConstants.YJ_SALE_FEES));
                if (null == walletInfo.getScore() || walletInfo.getScore().doubleValue() < total.doubleValue()) {
                    return ApiResult.fail("抵扣权益卡不足");
                }
                walletInfo.setMoney(BigDecimalUtil.subDouble(walletInfo.getMoney(), jybBusinessOrder.getNum()));

                walletInfo.setScore(BigDecimalUtil.subDouble(walletInfo.getScore(), total));
                if(! userBillService.addBillRecord("委托出售贡献值",ConfConstants.COMMISSION_TYPE,0,jybBusinessOrder.getNum(),userService.getUserId(),null)){
                    throw new RuntimeException("挂卖异常");
                }
                if(! userBillService.addBillRecord("委托出售贡献值抵扣权益卡",ConfConstants.INTEGRAL_TYPE,0,total,userService.getUserId(),null)){
                    throw new RuntimeException("挂卖异常");
                }
                if (jybBusinessOrderService.save(jybBusinessOrder)) {
                    if (walletService.updateById(walletInfo)) {
                        return ApiResult.ok("发布成功");
                    } else {
                        throw new RuntimeException("挂卖异常");
                    }

                }
            }

        }else{
            if (jybBusinessOrderService.save(jybBusinessOrder)) {
                    return ApiResult.ok("发布成功");

            }
        }
        return ApiResult.fail("失败");
    }

    /**
     * 修改数据
     */
    @ApiOperation(value = "修改数据")
    @PostMapping("/update")
    public ApiResult<?> update(@RequestBody @Validated JybBusinessOrderEntity jybBusinessOrder){
        if (jybBusinessOrderService.updateById(jybBusinessOrder)) {
            return ApiResult.ok();
        }
        return ApiResult.fail();
    }


    /**
     * 撤回挂卖
     */
    @ApiOperation(value = "撤回挂卖")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/revoke")
    public ApiResult<String> revoke( @RequestParam("id") Integer id){
        JybBusinessOrderEntity byId = jybBusinessOrderService.getById(id);
        if (null == byId || null ==byId.getId()){
            return ApiResult.fail("没有找到交易订单");
        }
        if (byId.getStatus() !=0){
            return ApiResult.fail("订单状态不匹配");
        }
        if (LoginUtil.getUserId().intValue() != byId.getUid().intValue()){
            return ApiResult.fail("不能撤销他人");
        }
        byId.setStatus(2);

        //挂买撤销订单返回余额
        if (byId.getType() == 1){
            LbUserWalletEntity walletInfo = walletService.getUserWalletInfo(byId.getUid());
            if (null == walletInfo || null == walletInfo.getId()) {
                return ApiResult.fail("没有找到钱包");
            }


            if (byId.getClassType() == 0){
                BigDecimal total =  BigDecimalUtil.mul(byId.getNum(), new BigDecimal(ConfConstants.HANG_SALE_FEES));
                //扣除手续费百分之比
                BigDecimal allPrice = BigDecimalUtil.addDouble(byId.getNum(),total);
                //退会收购人币
                walletInfo.setScore(BigDecimalUtil.addDouble(walletInfo.getScore(), allPrice));

                if(! userBillService.addBillRecord("退回权益卡",ConfConstants.INTEGRAL_TYPE,1,allPrice,userService.getUserId(),null)){
                    throw new RuntimeException("挂卖异常");
                }
            }else if (byId.getClassType() == 1){
                BigDecimal total =  BigDecimalUtil.mul(byId.getNum(), new BigDecimal(ConfConstants.YJ_SALE_FEES));
                //退回佣金和贡献值
                walletInfo.setScore(BigDecimalUtil.addDouble(walletInfo.getScore(), total));
                walletInfo.setMoney(BigDecimalUtil.addDouble(walletInfo.getMoney(), byId.getNum()));
                if(! userBillService.addBillRecord("退回贡献值",ConfConstants.COMMISSION_TYPE,1,byId.getNum(),userService.getUserId(),null)){
                    throw new RuntimeException("挂卖异常");
                }
                if(! userBillService.addBillRecord("退回抵扣权益卡",ConfConstants.INTEGRAL_TYPE,1,total,userService.getUserId(),null)){
                    throw new RuntimeException("挂卖异常");
                }
            }
            if (!walletService.updateById(walletInfo)) {
                return ApiResult.fail("取消异常，联系客服");
            }
        }
//    }

        if (jybBusinessOrderService.updateById(byId)){

                return ApiResult.ok("撤销成功");
        }else {
            throw new RuntimeException("取消异常，联系客服");
        }


    }

//    /**
//     * 明细记录
//     * @param title
//     * @param type
//     * @param pm
//     */
//    private boolean saveBill(String title,String type,Integer pm,BigDecimal num){
//        UserBill bill = new UserBill();
//        bill.setPm(pm);
//        bill.setTitle(title);
//        bill.setCategory(type);
//        bill.setCreateTime(new Date());
//        bill.setUid(userService.getUserId());
//        bill.setNumber(num);
//        return userBillService.save(bill);
//    }

}
